package com.luhui.commons.net;

import com.luhui.commons.util.FileUtils;
import com.luhui.commons.util.StringUtils;

import java.io.IOException;
import java.net.URLConnection;
import java.util.Map;

/**
 * Created with LXD
 *
 * @author:Luhui
 * @qq:729913162
 * @Date:2018-08-22
 * @Time:15:50
 */
class UrlConnectionUtils {

    public static URLConnection setProperty(URLConnection urlConnection,Request request){
        setProperty(urlConnection,"cookie",request.getCookie());
        setProperty(urlConnection,"referer",request.getRefer());
        setProperty(urlConnection,"user-agent",request.getUserAgent());
        Map<String, String> attributes = request.getAttributes();
        for(Map.Entry<String,String> entry : attributes.entrySet()){
            setProperty(urlConnection,entry.getKey(),entry.getValue());
        }
        return urlConnection;
    }

    private static URLConnection setProperty(URLConnection urlConnection,String key,String value){
        if(!StringUtils.isBlank(value)){
            urlConnection.addRequestProperty(key,value);
        }
        return urlConnection;
    }

    public static Response getResponse(URLConnection urlConnection,String charset) throws IOException {
        String cookie = urlConnection.getHeaderField("Set-Cookie");
        String html = FileUtils.readContext(urlConnection.getInputStream(),charset);
        return new Response(html,cookie);
    }
}
